package com.tql.test_05;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
ReadWriteLock 读写锁 细粒度
    同时只有一个线程去进行写操作（保证原子性）
    同时可以有多个线程去进行读操作
    独占锁（写锁） 保证原子性
    共享锁（读锁）
* */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        MeCatch2 meCatch=new MeCatch2();
        //获取读写锁
        ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
               meCatch.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
                meCatch.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}
class MeCatch2{
    private volatile Map<String,Object> map=new HashMap<>();
    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    public void put(String key,Object object){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写操作");
            map.put(key,object);
            System.out.println(Thread.currentThread().getName()+"完成写操作");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始读操作");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读操作");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
class MeCatch{
    private volatile Map<String,Object> map=new HashMap<>();
    public void put(String key,Object object){
        System.out.println(Thread.currentThread().getName()+"开始写操作");
        map.put(key,object);
        System.out.println(Thread.currentThread().getName()+"完成写操作写操作");
    }
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"开始读操作");
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"完成读操作写操作");
    }
}